package com.qfedu.service.impl;

import com.qfedu.dao.AccountDao;
import com.qfedu.dao.ProductDao;
import com.qfedu.dao.impl.AccountDaoImpl;
import com.qfedu.dao.impl.ProductDaoImpl;
import com.qfedu.pojo.Account;
import com.qfedu.pojo.MyProduct;
import com.qfedu.pojo.Product;
import com.qfedu.service.ProductService;
import com.qfedu.utils.JdbcUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.List;

public class ProductServiceImpl implements ProductService {
    private ProductDao productDao = new ProductDaoImpl();
    private AccountDao accountDao = new AccountDaoImpl();

    @Override
    public List<MyProduct> findMyProduct(String idcode) {
        return productDao.findMyProduct(idcode);
    }

    @Override
    public List<Product> findAllProducts() {
        return productDao.findAllProducts();
    }

    @Override
    public Product findProductById(int id) {
        return productDao.findProductById(id);
    }

    @Override
    public int payProduct(String idcode ,int pid,BigDecimal pnum, BigDecimal mon) {
        int i = 1;
        Connection connection = JdbcUtils.getConnection();
        try {
            JdbcUtils.begin(connection);
            accountDao.updateMoney(connection,idcode,mon);
            productDao.addMyProductById(connection,idcode,pid,pnum);
            JdbcUtils.commit(connection);
        } catch (Exception e) {
            JdbcUtils.rollback(connection);
            i=0;
            e.printStackTrace();
        }finally {
            JdbcUtils.close(connection);
        }
        return i;

    }

    @Override
    public MyProduct findMyProductByOnly(int id) {
        return productDao.findMyProductByOnly(id);
    }

    @Override
    public int backProduct(String idcode, Integer id, BigDecimal mon, int j,int leftNum) {
        int i = 1;
        Connection connection = JdbcUtils.getConnection();
        try {
            JdbcUtils.begin(connection);
            accountDao.updateMoney(connection,idcode,mon);
            if (j==0){
                productDao.deleteMyProductById(connection,id);
            }else {
                productDao.updateMyProductById(connection,id,leftNum);
            }
            JdbcUtils.commit(connection);
        } catch (Exception e) {
            JdbcUtils.rollback(connection);
            i=0;
            e.printStackTrace();
        }finally {
            JdbcUtils.close(connection);
        }
        return i;
    }

    @Override
    public BigDecimal backAllProductsPrice(String idcode) {
        return productDao.backAllProductsPrice(idcode);
    }
}
